package nxu.it;

import freemarker.template.Configuration;
import io.avaje.config.Config;
import io.avaje.http.api.AvajeJavalinPlugin;
import io.avaje.inject.Bean;
import io.avaje.inject.Factory;
import io.javalin.Javalin;
import io.javalin.http.staticfiles.Location;
import io.javalin.rendering.template.JavalinFreemarker;

import java.util.List;

@Factory
public class JavalinFactory {

    @Bean
    public Javalin javalin(List<AvajeJavalinPlugin> routes) {
        var app = Javalin.create(
                cfg -> {
                    routes.forEach(cfg::registerPlugin);
                    Configuration freemarkerConfig = new Configuration();
                    freemarkerConfig.setDefaultEncoding("utf-8");
                  //  freemarkerConfig.setCacheStorage(new NullCacheStorage());
                    freemarkerConfig.setClassForTemplateLoading(JavalinFactory.class, "/");
                    cfg.fileRenderer(new JavalinFreemarker(freemarkerConfig));
                    cfg.jetty.defaultPort = Config.getInt("server.port", 8080);
                    cfg.staticFiles.add(staticFileConfig -> {
                        staticFileConfig.hostedPath = "/static";
                        staticFileConfig.directory = "/static";
                        staticFileConfig.location = Location.CLASSPATH;
                    });
                }
        );
        return app;
    }
}
